package com.crm.system.service.impl.contractManager;

import com.alibaba.fastjson.JSON;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.DateUtil;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.vo.cluePoolManager.ForgetCustomerVO;
import com.crm.model.vo.cluePoolManager.NoContactCustomerDetailVO;
import com.crm.model.vo.cluePoolManager.NoContactCustomerVO;
import com.crm.service.cluePoolManager.ClueFollowDbService;
import com.crm.common.model.Enum.ForgetRemindEnum;
import com.crm.common.helper.PageHelper;
import com.crm.system.service.contractManager.ForgetRemindService;
import com.crm.system.service.customerManager.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: 遗忘提醒
 * @author: lixq-f
 * @create: 2021/03/25
 */
@Service
@Slf4j
public class ForgetRemindServiceImpl implements ForgetRemindService {


    @Autowired
    private ClueFollowDbService followDbService;
    @Autowired
    private CustomerService customerService;


    @Override
    public NoContactCustomerVO selectForgetRemindMsg() {

        //获取当前用户下所有客户
        List<Customer> customerList = customerService.getCustomerList();
        if (Objects.isNull(customerList)) {
            return new NoContactCustomerVO();
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<ForgetCustomerVO> forgetCustomerList = followDbService.selectForgetRemindMsg(userAccount.getAccountId());

        //log.info("selectForgetRemindMsg->forgetCustomerList:{}", JSON.toJSONString(forgetCustomerList));

        if (Objects.isNull(forgetCustomerList)) {
            return NoContactCustomerVO.getNoContactCustomer(0, 0, 0,
                    0, customerList.size());
        }

        LocalDate now = LocalDate.now();
        Date date7 = DateUtil.localDateToDate(now.minusDays(7));
        Date date15 = DateUtil.localDateToDate(now.minusDays(15));
        Date date30 = DateUtil.localDateToDate(now.minusDays(30));
        Date date60 = DateUtil.localDateToDate(now.minusDays(60));

        int count7 = (int) forgetCustomerList.stream()
                .filter(c -> Objects.nonNull(c.getFollowTm()) && c.getFollowTm().compareTo(date7) < 0).count();
        int count15 = (int) forgetCustomerList.stream()
                .filter(c -> Objects.nonNull(c.getFollowTm()) && c.getFollowTm().compareTo(date15) < 0).count();
        int count30 = (int) forgetCustomerList.stream()
                .filter(c -> Objects.nonNull(c.getFollowTm()) && c.getFollowTm().compareTo(date30) < 0).count();
        int count60 = (int) forgetCustomerList.stream()
                .filter(c -> Objects.nonNull(c.getFollowTm()) && c.getFollowTm().compareTo(date60) < 0).count();
        int overdue = customerList.size() - forgetCustomerList.size();

        NoContactCustomerVO result = NoContactCustomerVO.getNoContactCustomer(count7, count15, count30, count60, overdue);
        //log.info("selectForgetRemindMsg->result:{}", JSON.toJSONString(result));
        return result;
    }


    @Override
    public PageHelper<NoContactCustomerDetailVO> selectForgetRemindDetailsByPage(Integer pageIndex,
                                                                                 Integer pageSize,
                                                                                 int dataType,
                                                                                 Integer isMember) {

         List<NoContactCustomerDetailVO> detailVOList = new ArrayList<>();
        //获取当前用户下所有客户
        List<Customer> customerList = customerService.getCustomerList();
        if (Objects.isNull(customerList)) {
            return new PageHelper<>();
        }
        Map<String, Customer> customerMap = customerList
                .stream().collect(Collectors.toMap(Customer::getCustomerId, Customer -> Customer));

        List<ForgetCustomerVO> forgetCustomerList = getForgetCustomerList(dataType);

        NoContactCustomerDetailVO detailVO = null;

        //逾期
        if (ForgetRemindEnum.overdue.getCode() == dataType){
            if (!CollectionUtils.isEmpty(forgetCustomerList)){
                List<String> customerIdList = forgetCustomerList.stream()
                        .map(ForgetCustomerVO::getCustomerId).collect(Collectors.toList());
                customerList = customerList.stream()
                        .filter(c -> !customerIdList.contains(c.getCustomerId())).collect(Collectors.toList());
            }
            for (Customer customer : customerList) {
                detailVO = new NoContactCustomerDetailVO();
                BeanUtils.copyProperties(customer, detailVO);
                //客户类型转换
                customerTypeConvert(detailVO, customer);
                detailVOList.add(detailVO);
            }
        }else {
            //遗忘的客户
            for (ForgetCustomerVO forgetCustomerVO : forgetCustomerList) {
                Customer customer = customerMap.get(forgetCustomerVO.getCustomerId());
                if (Objects.nonNull(customer)){
                    detailVO = new NoContactCustomerDetailVO();
                    BeanUtils.copyProperties(customer, detailVO);
                    //客户类型转换
                    customerTypeConvert(detailVO, customer);
                    detailVO.setFollowTm(forgetCustomerVO.getFollowTm());
                    detailVOList.add(detailVO);
                }

            }
        }

        if (Objects.nonNull(isMember)) {
            if (0 == isMember) {
                //非会员
                detailVOList = detailVOList.stream()
                        .filter(c -> Objects.nonNull(c.getMembershipLevel()) && 0 == c.getMembershipLevel())
                        .collect(Collectors.toList());
            } else {
                detailVOList = detailVOList.stream()
                        .filter(c -> Objects.nonNull(c.getMembershipLevel()) && !(0 == c.getMembershipLevel()))
                        .collect(Collectors.toList());
            }
        }

        int total = detailVOList.size();
        int startIndex = (pageIndex - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize,total);
        PageHelper page = new PageHelper()
                .setPageIndex(pageIndex)
                .setPageSize(pageSize)
                .setCode(ResponseCodeEnum.OK.getResponseCode())
                .setMessage(ResponseCodeEnum.OK.getResponseValue())
                .setTotalRecords(total)
                .setData(detailVOList.subList(startIndex,endIndex));

        return page;
    }




    private void customerTypeConvert(NoContactCustomerDetailVO detailVO, Customer customer) {
        if(Objects.isNull(customer))
        return;

        String customerType = customer.getCustomerType();

        if (StringUtils.isEmpty(customerType)){
            detailVO.setCustomerType(customerType);
            return;
        }

        detailVO.setCustomerType("0".equals(customerType) ? "企业客户" : "个人客户");

    }


    private List<ForgetCustomerVO> getForgetCustomerList(Integer dataType) {

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        List<ForgetCustomerVO> forgetCustomerList = followDbService.selectForgetRemindMsg(userAccount.getAccountId());
        LocalDate now = LocalDate.now();
        if (ForgetRemindEnum.morethan_7days.getCode() == dataType) {
            Date date7 = DateUtil.localDateToDate(now.plusDays(-7));
            return forgetCustomerList.stream()
                    .filter(c -> Objects.nonNull(c.getFollowTm()) && c.getFollowTm().compareTo(date7) < 0)
                    .collect(Collectors.toList());
        }

        if (ForgetRemindEnum.morethan_15days.getCode() == dataType) {
            Date date15 = DateUtil.localDateToDate(now.plusDays(-15));
            return forgetCustomerList.stream()
                    .filter(c -> Objects.nonNull(c.getFollowTm()) && c.getFollowTm().compareTo(date15) < 0)
                    .collect(Collectors.toList());
        }

        if (ForgetRemindEnum.morethan_30days.getCode() == dataType) {
            Date date30 = DateUtil.localDateToDate(now.plusDays(-30));
            return forgetCustomerList.stream()
                    .filter(c -> Objects.nonNull(c.getFollowTm()) &&  c.getFollowTm().compareTo(date30) < 0)
                    .collect(Collectors.toList());
        }

        if (ForgetRemindEnum.morethan_2months.getCode() == dataType) {
            Date date60 = DateUtil.localDateToDate(now.plusDays(-60));
            return forgetCustomerList.stream()
                    .filter(c -> Objects.nonNull(c.getFollowTm()) && c.getFollowTm().compareTo(date60) < 0)
                    .collect(Collectors.toList());
        }

        if (ForgetRemindEnum.overdue.getCode() == dataType) {
            return forgetCustomerList;
        }


        return null;
    }



}
